package com.task.scheduler.persistence.entity;

import com.task.scheduler.enums.TaskExecutionMode;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 任务实体类，对应数据库表 tasks
 */
@Data
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Entity
@Table(name = "tasks", schema = "task_scheduler",
       indexes = {
           @Index(name = "idx_task_type", columnList = "task_type"),
           @Index(name = "idx_execution_mode", columnList = "execution_mode"),
           @Index(name = "idx_created_at", columnList = "created_at"),
           @Index(name = "idx_updated_at", columnList = "updated_at"),
           @Index(name = "idx_deleted", columnList = "deleted"),
           @Index(name = "idx_task_type_mode", columnList = "task_type, execution_mode"),
           @Index(name = "idx_active_tasks", columnList = "deleted, created_at")
       })
@EntityListeners(AuditingEntityListener.class)
public class TaskEntity {

    @Id
    @EqualsAndHashCode.Include
    @Column(name = "id", length = 36, nullable = false, columnDefinition = "VARCHAR(36) COMMENT '任务唯一ID（UUID）'")
    private String id;

    @Column(name = "task_type", nullable = false, length = 255, columnDefinition = "VARCHAR(255) NOT NULL COMMENT '任务类型'")
    private String taskType;

    @Column(name = "json_params", columnDefinition = "TEXT COMMENT '任务参数（JSON格式）'")
    private String jsonParams;

    @Column(name = "max_retry", nullable = false, columnDefinition = "INT DEFAULT 3 COMMENT '最大重试次数'")
    private int maxRetry = 3;

    @Column(name = "delay_seconds", nullable = false, columnDefinition = "BIGINT DEFAULT 0 COMMENT '延迟执行时间（秒）'")
    private long delaySeconds = 0L;

    @Enumerated(EnumType.STRING)
    @Column(name = "execution_mode", nullable = false, length = 20, columnDefinition = "VARCHAR(20) NOT NULL COMMENT '执行模式'")
    private TaskExecutionMode executionMode;

    @Column(name = "latest_execution_id", columnDefinition = "BIGINT NULL COMMENT '最新执行记录ID（外键）'")
    private Long latestExecutionId;

    // 软删除标记
    @Column(name = "deleted", nullable = false, columnDefinition = "BOOLEAN DEFAULT FALSE COMMENT '软删除标记'")
    private Boolean deleted = false;

    // 版本控制（乐观锁）
    @Version
    @Column(name = "version", nullable = false, columnDefinition = "BIGINT DEFAULT 0 COMMENT '版本号（乐观锁）'")
    private Long version = 0L;

    // 审计字段
    @CreatedDate
    @Column(name = "created_at", updatable = false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '任务创建时间'")
    private LocalDateTime createdAt;

    @LastModifiedDate
    @Column(name = "updated_at", columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最后更新时间'")
    private LocalDateTime updatedAt;

    // 关联关系 - 一对多执行记录
    @OneToMany(mappedBy = "task", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<TaskExecutionEntity> executions;

    // 业务方法
    
    /**
     * 软删除任务
     */
    public void softDelete() {
        this.deleted = true;
    }

    /**
     * 恢复已删除的任务
     */
    public void restore() {
        this.deleted = false;
    }

    /**
     * 判断任务是否已删除
     */
    public boolean isDeleted() {
        return Boolean.TRUE.equals(deleted);
    }

    /**
     * 判断是否为延迟任务
     */
    public boolean isDelayedTask() {
        return delaySeconds > 0;
    }

    /**
     * 获取预计执行时间
     */
    public LocalDateTime getExpectedExecutionTime() {
        if (createdAt == null) {
            return null;
        }
        return createdAt.plusSeconds(delaySeconds);
    }
}
